<!--
 * @Author: zhangweinan
 * @Date: 2023-02-02 13:42:38
 * @LastEditors: zhangweinan
 * @LastEditTime: 2023-03-02 10:47:17
 * @Description: file content
 * @FilePath: \front-end-of-task-center\src\components\bpmnProcessDesigner\package\penal\config\ApproverConfig.vue
-->
<template>
  <div>
    <div style="margin-bottom: 20px">
      <div class="titleConfig">审批人设置</div>
      <el-radio-group
        v-model="form.approverType"
        v-for="dict in taskAssignRuleTypeDictDatas"
        :key="dict.value"
        @change="updateElementDict"
      >
        <el-radio :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
      </el-radio-group>
      <div>
        <div v-if="form.approverType === 10" class="childSelect">
          <p>选择角色</p>
          <el-select
            v-model="form.roleIds"
            multiple
            clearable
            style="width: 100%"
            @change="updateElementRoleIds"
          >
            <el-option
              v-for="item in roleOptions"
              :key="parseInt(item.id)"
              :label="item.name"
              :value="parseInt(item.id)"
            />
          </el-select>
        </div>
        <div
          v-else-if="form.approverType === 20 || form.approverType === 21"
          class="childSelect"
        >
          <p>指定部门</p>
          <treeselect
            v-model="form.deptIds"
            :options="deptTreeOptions"
            multiple
            flat
            :defaultExpandLevel="3"
            placeholder="请选择指定部门"
            :normalizer="normalizer"
          />
        </div>
        <div v-else-if="form.approverType === 22" class="childSelect">
          <p>指定岗位</p>
          <el-select
            v-model="form.postIds"
            multiple
            clearable
            style="width: 100%"
            @change="updateElementPostIds"
          >
            <el-option
              v-for="item in postOptions"
              :key="parseInt(item.id)"
              :label="item.name"
              :value="parseInt(item.id)"
            />
          </el-select>
        </div>
        <div
          class="childSelect"
          v-else-if="
            form.approverType === 30 ||
            form.approverType === 31 ||
            form.approverType === 32
          "
        >
          <p>指定用户</p>
          <el-select
            v-model="form.userIds"
            multiple
            clearable
            style="width: 100%"
            filterable
            :filter-method="userFilter"
            @change="updateElementUserIds"
          >
            <el-option
              v-for="item in userOptions"
              :key="parseInt(item.id)"
              :label="item.nickname"
              :value="parseInt(item.id)"
            />
          </el-select>
        </div>
        <div v-else-if="form.approverType === 40" class="childSelect">
          <p>指定用户组</p>
          <el-select
            v-model="form.userGroupIds"
            multiple
            clearable
            style="width: 100%"
            @change="updateElementUserGroupIds"
          >
            <el-option
              v-for="item in userGroupOptions"
              :key="parseInt(item.id)"
              :label="item.name"
              :value="parseInt(item.id)"
            />
          </el-select>
        </div>
        <!-- <div v-else-if="form.approverType === 50" class="childSelect">
          <p>指定脚本</p>
          <el-select
            v-model="form.scripts"
            multiple
            clearable
            style="width: 100%"
            @change="updateElementScripts"
          >
            <el-option
              v-for="dict in taskAssignScriptDictDatas"
              :key="parseInt(dict.value)"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </div> -->
      </div>
    </div>
    <div v-show="isShowMultiPerson">
      <div class="titleConfig">多人审批方式</div>
      <el-radio-group
        v-model="multiPersonApproval"
        class="approvalClass"
        @change="updateMultiPersonApproval"
      >
        <el-radio label="ParallelMultiInstance"
          >会签(需所有审批人同意)</el-radio
        >
        <el-radio label="SequentialMultiInstance"
          >或签(一名审批人同意或拒绝即可)</el-radio
        >
        <!-- <el-radio :label="3">依次审批(按顺序依次审批)</el-radio> -->
      </el-radio-group>
    </div>
  </div>
</template>
<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { DICT_TYPE, getDictDatas } from "@/utils/dict";
import { listSimpleRoles } from "@/api/system/role";
import { listSimpleDepts } from "@/api/system/dept";
import { listSimplePosts } from "@/api/system/post";
import { listSimpleUsers } from "@/api/system/user";
import { listSimpleUserGroups } from "@/api/bpm/userGroup";
import {
  getUserGroupCount,
  getPostCount,
  getDeptCount,
  getRoleCount,
} from "@/api/system/count";
export default {
  name: "ApproverConfig",
  components: { Treeselect },
  props: {
    id: String,
    type: String,
  },
  data() {
    return {
      multiPersonApproval: "Null", //多人审批方式
      //数据字典
      taskAssignRuleTypeDictDatas: getDictDatas(
        DICT_TYPE.BPM_TASK_ASSIGN_RULE_TYPE
      ),
      //taskAssignScriptDictDatas: getDictDatas(DICT_TYPE.BPM_TASK_ASSIGN_SCRIPT),
      form: {
        approverType: 10, //默认是角色用户
        roleIds: [],
        deptIds: [],
        postIds: [],
        userIds: [],
        userGroupIds: [],
        scripts: [],
      },
      roleOptions: [],
      deptOptions: [],
      deptTreeOptions: [],
      postOptions: [],
      userOptions: [],
      allUserOptions: [],
      userGroupOptions: [],
      //是否显示多人审批界面
      isShowMultiPerson: true,
      elementVariable: "", //各个角色下的数量
    };
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        val && val.length && this.$nextTick(() => this.resetFormList());
      },
    },
    "form.deptIds": "updateElementDeptIds",
  },
  created() {
    //初始化审批人多人审批是否展示
    this.$nextTick(() => {
      this.isShowMultiPerson = this.initMulitPerson();
    });

    // 获得角色列表
    this.roleOptions = [];
    listSimpleRoles().then((response) => {
      this.roleOptions.push(...response.data);
    });

    // 获得部门列表
    this.deptOptions = [];
    this.deptTreeOptions = [];
    listSimpleDepts().then((response) => {
      this.deptOptions.push(...response.data);
      this.deptTreeOptions.push(...this.handleTree(response.data, "id"));
    });
    // 获得岗位列表
    this.postOptions = [];
    listSimplePosts().then((response) => {
      this.postOptions.push(...response.data);
    });
    // 获得用户列表
    this.allUserOptions = [];
    listSimpleUsers().then((response) => {
      this.allUserOptions.push(...response.data);
      this.userFilter();
    });
    // 获得用户组列表
    this.userGroupOptions = [];
    listSimpleUserGroups().then((response) => {
      this.userGroupOptions.push(...response.data);
    });
  },
  methods: {
    //初始化配置
    resetFormList() {
      this.bpmnELement = window.bpmnInstances.bpmnElement;
      //初始化朝xml里添加审批人类型
      let { roleIds, userGroupIds, deptIds, userIds, postIds } =
        this.bpmnELement.businessObject;
      //初始化的时候，重置form里的数据
      this.form.approverType = 10;
      this.form.roleIds = [];
      this.form.userIds = [];
      this.form.userGroupIds = [];
      this.form.deptIds = [];
      this.form.postIds = [];
      if (userGroupIds !== undefined && userGroupIds.length > 0) {
        this.form.userGroupIds = Array.isArray(userGroupIds)
          ? userGroupIds
          : userGroupIds.split(",").map((item) => Number(item));
      }
      if (roleIds !== undefined && roleIds.length > 0) {
        this.form.roleIds = Array.isArray(roleIds)
          ? roleIds
          : roleIds.split(",").map((item) => Number(item));
      }
      if (postIds !== undefined && postIds.length > 0) {
        this.form.postIds = Array.isArray(postIds)
          ? postIds
          : postIds.split(",").map((item) => Number(item));
      }
      if (deptIds !== undefined && deptIds.length > 0) {
        this.form.deptIds = Array.isArray(deptIds)
          ? deptIds
          : deptIds.split(",").map((item) => Number(item));
      }
      if (userIds !== undefined && userIds.length > 0) {
        this.form.userIds = Array.isArray(userIds)
          ? userIds
          : userIds.split(",").map((item) => Number(item));
      }
      this.form.approverType = this.bpmnELement.businessObject.approverType
        ? Number(this.bpmnELement.businessObject.approverType)
        : 10;
      this.multiPersonApproval =
        this.bpmnELement.businessObject.multiPersonApproval;
      //alert(this.multiPersonApproval);
      //alert(this.bpmnELement.businessObject.multiPersonApproval);
      this.isShowMultiPerson = this.initMulitPerson();
      //根据approberType去获取用户数量
      this.initApproverType();
    },
    //初始化角色类型
    initApproverType() {
      let approverType = this.form.approverType;
      if (approverType === 10) {
        if (this.form.roleIds.length == 0) {
          window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
            approverType: 10,
          });
          this.multiPersonApproval = "Null";
          return;
        }
        getRoleCount(this.form.roleIds).then((res) => {
          this.elementVariable = res.data;
          this.initUpdateInstance();
        });
      } else if (approverType === 21 || approverType === 20) {
        if (this.form.deptIds.length == 0) {
          this.multiPersonApproval = "Null";
          return;
        }
        getDeptCount(this.form.deptIds).then((res) => {
          this.elementVariable = res.data;
          this.initUpdateInstance();
        });
      } else if (approverType === 22) {
        if (this.form.postIds.length == 0) {
          this.multiPersonApproval = "Null";
          return;
        }
        getPostCount(this.form.postIds).then((res) => {
          this.elementVariable = res.data;
          this.initUpdateInstance();
        });
      } else if (approverType === 40) {
        if (this.form.userGroupIds.length == 0) {
          this.multiPersonApproval = "Null";
          return;
        }
        getUserGroupCount(this.form.userGroupIds).then((res) => {
          this.elementVariable = res.data;
          this.initUpdateInstance();
        });
      } else {
        // this.elementVariable = this.form.userIds.length;
        if (this.form.userIds.length > 1) {
          this.multiPersonApproval =
            this.multiPersonApproval !== "Null"
              ? this.multiPersonApproval
              : "SequentialMultiInstance";
        } else {
          this.multiPersonApproval = "Null";
        }
        window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
          multiPersonApproval: this.multiPersonApproval,
        });
        this.$emit("updateMultinstance", {
          type: this.multiPersonApproval,
          num: this.form.userIds.length,
        });
      }
    },
    // 格式化部门的下拉框
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    //过滤用户数据
    userFilter(query = "") {
      let arr = this.allUserOptions.filter((item) => {
        return item.nickname.includes(query) || String(item.id) == query;
      });
      if (arr.length > 50) {
        this.userOptions = arr.slice(0, 50);
      } else {
        this.userOptions = arr;
      }
      if (this.form.userIds.length > 0) {
        let that = this;
        that.form.userIds.forEach((element) => {
          that.addFilterOptions(element);
        });
      }
    },
    addFilterOptions(label) {
      // 每次查找输入时，若有精确匹配的条目，保证该条目一定在renderOption内
      let target = this.allUserOptions.find((item) => {
        // 从大option中找到当前条
        return String(item.id) == String(label);
      });
      if (target) {
        // 将当前条与小option比对，没有则加入
        if (
          this.userOptions.every(
            (item) => String(item.id) !== String(target.id)
          )
        ) {
          this.userOptions.unshift(target);
        }
      }
    },
    updateElementRoleIds() {
      this.getCount("role", this.form.roleIds);
      this.isShowMultiPerson = true;
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        roleIds: this.form.roleIds,
      });
    },
    updateElementDict() {
      this.multiPersonApproval = "Null";
      this.$emit("updateMultinstance", {
        type: this.multiPersonApproval,
        num: "",
      });
      this.isShowMultiPerson = this.initMulitPerson();
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        approverType: this.form.approverType,
      });
      this.resetForm();
    },
    updateElementDeptIds() {
      if (this.form.approverType !== 20 && this.form.approverType !== 21)
        return;
      this.getCount("dept", this.form.deptIds);
      this.isShowMultiPerson = true;
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        deptIds: this.form.deptIds,
      });
    },
    updateElementScripts() {
      this.isShowMultiPerson = true;
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        scripts: this.form.scripts,
      });
    },
    updateElementUserGroupIds() {
      this.getCount("userGroup", this.form.userGroupIds);
      this.isShowMultiPerson = true;
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        userGroupIds: this.form.userGroupIds,
      });
    },
    updateElementUserIds() {
      this.elementVariable = this.form.userIds.length;
      this.isShowMultiPerson = this.form.userIds.length > 1;
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        userIds: this.form.userIds,
      });
      if (this.form.userIds.length < 2) {
        this.multiPersonApproval = "Null";
        this.$emit("updateMultinstance", {
          type: this.multiPersonApproval,
          num: 0,
        });
      } else {
        this.multiPersonApproval = "SequentialMultiInstance";
        this.$emit("updateMultinstance", {
          type: this.multiPersonApproval,
          num: this.form.userIds.length,
        });
      }
    },
    updateElementPostIds() {
      this.getCount("post", this.form.postIds);
      this.isShowMultiPerson = true;
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        postIds: this.form.postIds,
      });
    },
    updateMultiPersonApproval(val) {
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        multiPersonApproval: this.multiPersonApproval,
      });
      this.$emit("updateMultinstance", {
        type: val,
        num: this.elementVariable,
      });
    },
    //重置表单
    resetForm() {
      //this.form.approverType = 10;
      this.form.deptIds = [];
      this.form.roleIds = [];
      this.form.postIds = [];
      this.form.userGroupIds = [];
      this.form.userIds = [];
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        approverType: this.form.approverType,
      });
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        deptIds: this.form.deptIds,
      });
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        roleIds: this.form.roleIds,
      });
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        postIds: this.form.postIds,
      });
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        userGroupIds: this.form.userGroupIds,
      });
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
        userIds: this.form.userIds,
      });
    },
    //封装函数-多人审批方式设置初始化
    initMulitPerson() {
      let state = true;
      if (
        [30, 32, 32].includes(this.form.approverType) &&
        this.form.userIds.length < 2
      ) {
        state = false;
      } else {
        state = true;
      }
      return state;
    },
    //获取各个角色配置的数量
    getCount(type, val) {
      val = val.length === 0 ? 0 : val;
      //获取用户组数量
      this.elementVariable = "";
      switch (type) {
        case "userGroup":
          getUserGroupCount(val).then((res) => {
            this.elementVariable = res.data;
            this.initUpdateInstance();
          });
          break;
        case "dept":
          getDeptCount(val).then((res) => {
            this.elementVariable = res.data;
            this.initUpdateInstance();
          });
          break;
        case "role":
          getRoleCount(val).then((res) => {
            this.elementVariable = res.data;
            this.initUpdateInstance();
          });
          break;
        case "post":
          getPostCount(val).then((res) => {
            this.elementVariable = res.data;
            this.initUpdateInstance();
          });
          break;
      }
    },
    //初始化是否更新实例
    initUpdateInstance() {
      if (this.elementVariable > 0) {
        this.multiPersonApproval =
          this.multiPersonApproval !== "Null"
            ? this.multiPersonApproval
            : "SequentialMultiInstance";
        window.bpmnInstances.modeling.updateProperties(this.bpmnELement, {
          multiPersonApproval: this.multiPersonApproval,
        });
        if (
          this.multiPersonApproval === "SequentialMultiInstance" ||
          this.multiPersonApproval === "ParallelMultiInstance"
        ) {
          this.$emit("updateMultinstance", {
            type: this.multiPersonApproval,
            num: this.elementVariable,
          });
        }
      }
    },
  },
  method: {},
};
</script>
<style lang="scss" scoped>
.approvalClass {
  display: flex;
  flex-direction: column;
}
.titleConfig {
  font-size: 16px;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;
  font-weight: 600;
  color: #333333;
  margin-bottom: 15px;
}
.childSelect {
  p {
    font-size: 14px;
    font-family: SourceHanSansCN-Medium, SourceHanSansCN;
    font-weight: 600;
    color: #333333;
  }
  box-sizing: border-box;
  padding: 0 20px;
}
::v-deep .el-radio {
  margin-right: 20px;
  margin-bottom: 8px;
}
</style>
